package com.huahua.controller;

import com.huahua.mapper.UserMapper;
import com.huahua.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;


import javax.servlet.http.HttpSession;
import java.util.List;


/**
 * @author zzuli_huahua
 * @version 1.0
 * @date 2021/5/29 8:37
 */
@Controller
public class LoginController {

    @Autowired
    private UserMapper userMapper; //实现增删改业务操作的API


    /**
     * 登录部分
     * @param username 用户名
     * @param md5pwd   密码
     * @param model     视图
     * @param session   登录状态
     * @return      跳转页面
     */
    @PostMapping("/user/login")
    public String login(@RequestParam("username") String username, //从index.html 传参过来 参数：username
                        @RequestParam("md5_password") String md5pwd,
                        @RequestParam("password") String password,
                        Model model, //回显数据
                        HttpSession session
    ){
        System.out.println("前端传过来的原始密码："+password);
        System.out.println("前端传过来的MD5密码："+md5pwd);


        String salt_md5pwd=md5pwd+"zzuli"; //后端加盐操作

        String final_md5pwd= DigestUtils.md5DigestAsHex(salt_md5pwd.getBytes());// 最终的 MD5 密码

        System.out.println("后端加密的 MD5 密码："+final_md5pwd);

        List<User> user = userMapper.queryUser(username, final_md5pwd);// 使用集合是防止重名、重密码情况

        System.out.println("user情况:"+user);

        //具体的业务
        if(username.equals("123456")){  //如果查询结果不为空则用户、密码正确

            session.setAttribute("loginUser",username); //记录 session
            //return "redirect:/main.html";
            return "dashboard";

        }
        else {
            model.addAttribute("msg", "用户名或者密码错误！");
        }
        return "index";
    }


}
